﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using SmartFrame_DataCollect.Models;
using System.Data.SqlClient;
using HslCommunicationDemo;
using ServiceStack;

namespace SmartFrame_DataCollect
{
    public partial class DeviceDetails : BaseModule
    {
        public List<CollectVarConfig> ListCollectVarConfig = new List<CollectVarConfig>();
        public List<CollectJSONConfig> ListCollectJSONConfig = new List<CollectJSONConfig>();
        public List<CollectWebAPIConfig> ListCollectWebAPIConfig = new List<CollectWebAPIConfig>();

        //采集数据库名称
        string msSQLDBName = DataBaseHelper.CJDBName;
        public string curEuipID = "0";
        //复制采集字段列表
        static List<CollectVarConfig> CopyCollectVarConfigList = new List<CollectVarConfig>();
        static List<CollectJSONConfig> CopyCollectJSONConfigList = new List<CollectJSONConfig>();
        static List<CollectWebAPIConfig> CopyCollectWebAPIConfig = new List<CollectWebAPIConfig>();
        //选中WebAPI主表
        public CollectWebAPIConfig CurrentWebAPIConfig = null;

        public DeviceDetails()
        {
            InitializeComponent();
            //InitControlConfig();

            repositoryItemComboBox1.Items.Add("数组");
            repositoryItemComboBox1.Items.Add("对象");
            repositoryItemComboBox1.Items.Add("属性");
            repositoryItemComboBox1.Items.Add("参数名");
            repositoryItemComboBox1.Items.Add("参数值");


            repositoryItemComboBox2.Items.Add("数组");
            repositoryItemComboBox2.Items.Add("对象");
            repositoryItemComboBox2.Items.Add("属性");
            repositoryItemComboBox2.Items.Add("参数名");
            repositoryItemComboBox2.Items.Add("参数值");

            treeJSONConfig.ParentFieldName = "ParentID";
            treeJSONConfig.KeyFieldName = "EquipJSONConfigID";

            treeWebAPIDetailConfig.ParentFieldName = "ParentID";
            treeWebAPIDetailConfig.KeyFieldName = "EquipWebAPIConfigDeID";


            repositoryItemMemoExEdit1.ShowIcon = false;


        }

        public void InitControlConfig()
        {
            //显示设备详细名称
            DataTable dtEquipment = DbHelperSQL.Query("select * from Ba_Equipment where EquipmentID=" + curEuipID + "").Tables[0];
            if (dtEquipment.Rows.Count > 0)
            {
                lblEquipName.Text = dtEquipment.Rows[0]["EquipmentName"].ToString() + " " + dtEquipment.Rows[0]["EquipmentCode"] + "【" + dtEquipment.Rows[0]["EquipmentSpec"] + "】";
            }
            //获取当前配置项内容
            string sql = @"if not exists(select * from " + msSQLDBName + ".dbo.Ba_EquipConfig where EquipID=" + curEuipID + @") 
                           begin
                             insert into " + msSQLDBName + @".dbo.[Ba_EquipConfig](EquipID)
                             values(" + curEuipID + @")
                           end";
            DbHelperSQL.Query(sql);
            //获取设备协议配置项
            DataTable dtConfig = DbHelperSQL.Query("select * from " + msSQLDBName + ".dbo.Ba_EquipConfig where EquipID=" + curEuipID).Tables[0];
            protocolConfig.EditValue = dtConfig.Rows[0]["ProtocolConfig"].ToString();
            cbEditDataBase.SelectedItem = dtConfig.Rows[0]["DataBaseConfig"].ToString();
            editSaveDataTime.EditValue = dtConfig.Rows[0]["SaveDataTime"].ToString();
            editRunRangeTime.EditValue = dtConfig.Rows[0]["RunRangeTime"].ToString();

            //获取设备参数配置项
            DataTable dtVarConfig = DbHelperSQL.Query("select * from " + msSQLDBName + ".dbo.Ba_EquipVarConfig where EquipID=" + curEuipID).Tables[0];
            ListCollectVarConfig = new List<CollectVarConfig>();
            foreach (DataRow dr in dtVarConfig.Rows)
            {
                CollectVarConfig varConfigObj = new CollectVarConfig();
                varConfigObj.VarConfigID = dr["EquipVarConfigID"].ToString();
                varConfigObj.VarIsChecked = false;
                varConfigObj.VarName = dr["VarName"].ToString();
                varConfigObj.VarRequency = dr["VarRequency"].ToString();
                varConfigObj.VarSpecial = dr["VarSpecial"].ToString();
                varConfigObj.VarPath = dr["VarPath"].ToString();
                varConfigObj.VarType = dr["VarType"].ToString();
                ListCollectVarConfig.Add(varConfigObj);
            }
            bindCollectVarConfig();

            //获取设备JSON参数配置项
            DataTable dtJSONConfig = DbHelperSQL.Query("select * from " + msSQLDBName + ".dbo.Ba_EquipJSONConfig where EquipID=" + curEuipID).Tables[0];
            ListCollectJSONConfig = new List<CollectJSONConfig>();
            foreach (DataRow dr in dtJSONConfig.Rows)
            {
                CollectJSONConfig jsonConfig = new CollectJSONConfig();
                jsonConfig.EquipJSONConfigID = dr["EquipJSONConfigID"].ToString();
                jsonConfig.EquipID = int.Parse(dr["EquipID"].ToString());
                jsonConfig.ParentID = dr["ParentID"].ToString();
                jsonConfig.NodeName = dr["NodeName"].ToString();
                jsonConfig.NodeType = dr["NodeType"].ToString();
                ListCollectJSONConfig.Add(jsonConfig);
            }
            bindCollectJSONConfig();

            //获取设备WebAPI接口参数配置项
            DataTable dtWebAPIConfig = DbHelperSQL.Query("select * from " + msSQLDBName + ".dbo.Ba_EquipWebAPIConfig where EquipID=" + curEuipID).Tables[0];
            ListCollectWebAPIConfig = new List<CollectWebAPIConfig>();
            foreach (DataRow dr in dtWebAPIConfig.Rows)
            {
                CollectWebAPIConfig webapiConfig = new CollectWebAPIConfig();
                webapiConfig.EquipWebAPIConfigID = int.Parse(dr["EquipWebAPIConfigID"].ToString());
                webapiConfig.EquipID = int.Parse(dr["EquipID"].ToString());
                webapiConfig.ParamUrl = dr["ParamUrl"].ToString();
                webapiConfig.listDetailConfig = new List<CollectWebAPIDetailConfig>();

                //获取设备WebAPI接口参数配置项
                DataTable dtWebAPIDeConfig = DbHelperSQL.Query("select * from " + msSQLDBName + ".dbo.Ba_EquipWebAPIDetailConfig where EquipWebAPIConfigID=" + webapiConfig.EquipWebAPIConfigID).Tables[0];
                foreach (DataRow detailDr in dtWebAPIDeConfig.Rows)
                {
                    CollectWebAPIDetailConfig webapiDetailConfig = new CollectWebAPIDetailConfig();
                    webapiDetailConfig.EquipWebAPIConfigDeID = detailDr["EquipWebAPIConfigDeID"].ToString();
                    webapiDetailConfig.EquipWebAPIConfigID = int.Parse(detailDr["EquipWebAPIConfigID"].ToString());
                    webapiDetailConfig.ParentID = detailDr["ParentID"].ToString();
                    webapiDetailConfig.NodeName = detailDr["NodeName"].ToString();
                    webapiDetailConfig.NodeType = detailDr["NodeType"].ToString();
                    webapiConfig.listDetailConfig.Add(webapiDetailConfig);
                }
                ListCollectWebAPIConfig.Add(webapiConfig);
            }
            bindCollectWebAPIConfig();







        }

        public void bindCollectVarConfig()
        {
            gridVarConfig.DataSource = ListCollectVarConfig;
            gridVarConfig.RefreshDataSource();
        }

        public void bindCollectJSONConfig()
        {
            treeJSONConfig.DataSource = ListCollectJSONConfig;
            treeJSONConfig.RefreshDataSource();
        }

        public void bindCollectWebAPIConfig()
        {
            gridWebAPI.DataSource = ListCollectWebAPIConfig;
            gridWebAPI.RefreshDataSource();
        }

        public void UpdateContent()
        {
            string sbinfo = this.lblEquipName.Text;
            sbinfo = "112";
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var varNewConfig = new CollectVarConfig();
            varNewConfig.VarIsChecked = false;
            ListCollectVarConfig.Add(varNewConfig);
            bindCollectVarConfig();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            //repositoryItemCheckEdit1
            var collectVarConfigList = gridVarConfig.DataSource as List<CollectVarConfig>;
            ListCollectVarConfig = collectVarConfigList.Where(x => x.VarIsChecked == false).ToList();
            bindCollectVarConfig();
        }

        private void barItmSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //保存设备采集配置项
            string sql = "update " + msSQLDBName + ".dbo.Ba_EquipConfig set ProtocolConfig=@ProtocolConfig,DataBaseConfig=@DataBaseConfig,SaveDataTime=@SaveDataTime,RunRangeTime=@RunRangeTime where EquipID=@EquipID  ";
            DbHelperSQL.Query(sql, new SqlParameter[] {
                new SqlParameter("ProtocolConfig",protocolConfig.EditValue.ToString()),
                new SqlParameter("DataBaseConfig",cbEditDataBase.SelectedItem.ToString()),
                new SqlParameter("SaveDataTime",editSaveDataTime.EditValue.ToString()),
                new SqlParameter("RunRangeTime",editRunRangeTime.EditValue.ToString()),
                new SqlParameter("EquipID",curEuipID)
            });
            //保存设备参数配置项
            //批量删除
            DbHelperSQL.Query("delete " + msSQLDBName + ".dbo.Ba_EquipVarConfig where EquipID=" + curEuipID + "");
            //批量新增
            var collectVarConfigList = gridVarConfig.DataSource as List<CollectVarConfig>;
            foreach (var item in collectVarConfigList)
            {
                string varSql = "insert into " + msSQLDBName + ".dbo.Ba_EquipVarConfig(EquipID,VarName,VarPath,VarSpecial,VarType,VarRequency) values(@EquipID,@VarName,@VarPath,@VarSpecial,@VarType,@VarRequency) ";
                DbHelperSQL.Query(varSql, new SqlParameter[] {
                    new SqlParameter("EquipID",curEuipID),
                    new SqlParameter("VarName",item.VarName),
                    new SqlParameter("VarPath",item.VarPath),
                    new SqlParameter("VarSpecial",item.VarSpecial),
                    new SqlParameter("VarRequency",item.VarRequency),
                    new SqlParameter("VarType",item.VarType)
                });
            }

            DbHelperSQL.Query("delete " + msSQLDBName + ".dbo.Ba_EquipJSONConfig where EquipID=" + curEuipID + "");
            //批量新增
            var collectTreeJSONConfig = treeJSONConfig.DataSource as List<CollectJSONConfig>;

            foreach (var item in collectTreeJSONConfig)
            {
                string varSql = "insert into " + msSQLDBName + ".dbo.Ba_EquipJSONConfig(EquipJSONConfigID,EquipID,ParentID,NodeName,NodeType) values(@EquipJSONConfigID,@EquipID,@ParentID,@NodeName,@NodeType) ";
                DbHelperSQL.Query(varSql, new SqlParameter[] {
                    new SqlParameter("EquipJSONConfigID",item.EquipJSONConfigID),
                    new SqlParameter("EquipID",curEuipID),
                    new SqlParameter("ParentID",item.ParentID),
                    new SqlParameter("NodeName",item.NodeName),
                    new SqlParameter("NodeType",item.NodeType)
                });
            }
            //WebAPI接口参数
            DbHelperSQL.Query("delete " + msSQLDBName + ".dbo.Ba_EquipWebAPIDetailConfig where EquipWebAPIConfigID in (select EquipWebAPIConfigID from " + msSQLDBName + ".dbo.Ba_EquipWebAPIConfig where EquipID=" + curEuipID + " )  ");
            DbHelperSQL.Query("delete " + msSQLDBName + ".dbo.Ba_EquipWebAPIConfig where EquipID=" + curEuipID + "");

            var collectWebAPIConfig = gridWebAPI.DataSource as List<CollectWebAPIConfig>;
            foreach (var item in collectWebAPIConfig)
            {
                string webAPISql = "insert into  " + msSQLDBName + ".dbo.Ba_EquipWebAPIConfig(EquipID,ParamUrl) values(@EquipID,@ParamUrl) select @@identity as EquipWebAPIConfigID ";
                int EquipWebAPIConfigID = int.Parse(DbHelperSQL.Query(webAPISql, new SqlParameter[] {
                    new SqlParameter("EquipID",curEuipID),
                    new SqlParameter("ParamUrl",item.ParamUrl)
                }).Tables[0].Rows[0]["EquipWebAPIConfigID"].ToString());
                foreach (var item2 in item.listDetailConfig)
                {
                    string webAPISql2 = "insert into " + msSQLDBName + ".dbo.Ba_EquipWebAPIDetailConfig(EquipWebAPIConfigDeID,EquipWebAPIConfigID,ParentID,NodeName,NodeType) values(@EquipWebAPIConfigDeID,@EquipWebAPIConfigID,@ParentID,@NodeName,@NodeType) ";
                    DbHelperSQL.Query(webAPISql2, new SqlParameter[] {
                        new SqlParameter("EquipWebAPIConfigDeID",item2.EquipWebAPIConfigDeID),
                        new SqlParameter("EquipWebAPIConfigID",EquipWebAPIConfigID),
                        new SqlParameter("ParentID",item2.ParentID),
                        new SqlParameter("NodeName",item2.NodeName),
                        new SqlParameter("NodeType",item2.NodeType)
                    });
                }
            }
            XtraMessageBox.Show("参数配置已保存,请重新开启采集任务", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void barItemConfigProtocol_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //确认协议名称
            //ProtocalInfo protocalInfo = new ProtocalInfo();
            //protocalInfo.TypeName = "Siemens Plc [西门子]";
            //protocalInfo.TypeDetailName = "S7-S1200";
            //protocalInfo.ConnectConfig = "";
            WRProtocal.WriteProtocal(protocolConfig.EditValue.ToString());

            System.Threading.ThreadPool.SetMaxThreads(2000, 800);
            FormMain formMain = new FormMain(protocolConfig.EditValue.ToString());
            formMain.FormClosed += FormMain_FormClosed;
            formMain.Show();
        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            //读取协议配置项内容
            string protocalJson = WRProtocal.ReadProtocal();
            protocolConfig.EditValue = protocalJson;
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            CollectJSONConfig collectJSONConfig = new CollectJSONConfig();
            var selectionNodes = treeJSONConfig.Selection;
            if (selectionNodes.Count > 0)
            {
                var id = selectionNodes[0].GetValue("EquipJSONConfigID");
                collectJSONConfig.ParentID = id.ToString();
                collectJSONConfig.NodeName = "新节点";
                collectJSONConfig.NodeType = "属性";
                collectJSONConfig.EquipJSONConfigID = Guid.NewGuid().ToString("N");
                ListCollectJSONConfig.Add(collectJSONConfig);
                bindCollectJSONConfig();
            }
            else
            {
                collectJSONConfig.ParentID = new Guid().ToString("N");
                collectJSONConfig.NodeName = "新节点";
                collectJSONConfig.NodeType = "属性";
                collectJSONConfig.EquipJSONConfigID = Guid.NewGuid().ToString("N");
                ListCollectJSONConfig.Add(collectJSONConfig);
                bindCollectJSONConfig();
            }


        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            var selectionNodes = treeJSONConfig.Selection;
            if (selectionNodes.Count > 0)
            {
                var id = selectionNodes[0].GetValue("EquipJSONConfigID").ToString();
                ListCollectJSONConfig = ListCollectJSONConfig.Where(x => x.EquipJSONConfigID != id).ToList();
                bindCollectJSONConfig();
            }
        }

       

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            CopyCollectVarConfigList = (gridVarConfig.DataSource as List<CollectVarConfig>).ToJSON().FromJSON<List<CollectVarConfig>>();
            XtraMessageBox.Show("复制成功");
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            if (CopyCollectVarConfigList.Count > 0)
            {
                gridVarConfig.DataSource = CopyCollectVarConfigList.ToJSON().FromJSON<List<CollectVarConfig>>();
            }
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            CopyCollectJSONConfigList =  (treeJSONConfig.DataSource as List<CollectJSONConfig>).ToJSON().FromJSON<List<CollectJSONConfig>>();
            XtraMessageBox.Show("复制成功");
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            if (CopyCollectJSONConfigList.Count > 0)
            {
                var pasteJSONConfig = CopyCollectJSONConfigList.ToJSON().FromJSON<List<CollectJSONConfig>>();
                foreach (CollectJSONConfig item in pasteJSONConfig)
                {
                    string oldConfigID = item.EquipJSONConfigID;
                    item.EquipJSONConfigID = Guid.NewGuid().ToString("N");
                    //所有父级节点的都统一更改
                    var childOldConfig = pasteJSONConfig.Where(x => x.ParentID == oldConfigID).ToList();
                    foreach (var childItem in childOldConfig)
                    {
                        childItem.ParentID = item.EquipJSONConfigID;
                    }
                }
                treeJSONConfig.DataSource = pasteJSONConfig;
            }
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            var webAPINewConfig = new CollectWebAPIConfig();
            webAPINewConfig.listDetailConfig = new List<CollectWebAPIDetailConfig>();
            ListCollectWebAPIConfig.Add(webAPINewConfig);
            bindCollectWebAPIConfig();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            //var selectionNodes = gridWebAPI.;
            //if (selectionNodes.Count > 0)
            //{
            //    var id = selectionNodes[0].GetValue("EquipJSONConfigID").ToString();
            //    ListCollectJSONConfig = ListCollectJSONConfig.Where(x => x.EquipJSONConfigID != id).ToList();
            //    bindCollectJSONConfig();
            //}

            var collectWebAPIConfigList = gridWebAPI.DataSource as List<CollectWebAPIConfig>;
            ListCollectWebAPIConfig = collectWebAPIConfigList.Where(x => x.webAPIChecked == false).ToList();
            bindCollectWebAPIConfig();
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            if(CurrentWebAPIConfig!=null)
            {
                CollectWebAPIDetailConfig collectWebAPIDetailConfig = new CollectWebAPIDetailConfig();
                var selectionNodes = treeWebAPIDetailConfig.Selection;
                if (selectionNodes.Count > 0)
                {
                    var id = selectionNodes[0].GetValue("EquipWebAPIConfigDeID");
                    collectWebAPIDetailConfig.ParentID = id.ToString();
                    collectWebAPIDetailConfig.NodeName = "新节点";
                    collectWebAPIDetailConfig.NodeType = "属性";
                    collectWebAPIDetailConfig.EquipWebAPIConfigDeID = Guid.NewGuid().ToString("N");
                    CurrentWebAPIConfig.listDetailConfig.Add(collectWebAPIDetailConfig);
                    treeWebAPIDetailConfig.DataSource = CurrentWebAPIConfig.listDetailConfig;
                    treeWebAPIDetailConfig.RefreshDataSource();
                }
                else
                {
                    collectWebAPIDetailConfig.ParentID = new Guid().ToString("N");
                    collectWebAPIDetailConfig.NodeName = "新节点";
                    collectWebAPIDetailConfig.NodeType = "属性";
                    collectWebAPIDetailConfig.EquipWebAPIConfigDeID = Guid.NewGuid().ToString("N");
                    CurrentWebAPIConfig.listDetailConfig.Add(collectWebAPIDetailConfig);
                    treeWebAPIDetailConfig.DataSource = CurrentWebAPIConfig.listDetailConfig;
                    treeWebAPIDetailConfig.RefreshDataSource();
                }
            }
        }

        private void toolStripButton13_Click(object sender, EventArgs e)
        {
            var collectWebAPIConfigList = gridWebAPI.DataSource as List<CollectWebAPIConfig>;
            var checkList = collectWebAPIConfigList.Where(x => x.webAPIChecked == true).ToList();
            if(checkList.Count>0)
            {
                CurrentWebAPIConfig = checkList[0];
            }
            //更新列表
            treeWebAPIDetailConfig.DataSource = CurrentWebAPIConfig.listDetailConfig ;
            treeWebAPIDetailConfig.RefreshDataSource();


        }

        private void toolStripButton12_Click(object sender, EventArgs e)
        {
            if(CurrentWebAPIConfig!=null)
            {
                var selectionNodes = treeWebAPIDetailConfig.Selection;
                if (selectionNodes.Count > 0)
                {
                    var id = selectionNodes[0].GetValue("EquipWebAPIConfigDeID").ToString();
                    CurrentWebAPIConfig.listDetailConfig = CurrentWebAPIConfig.listDetailConfig.Where(x => x.EquipWebAPIConfigDeID != id).ToList();
                    treeWebAPIDetailConfig.DataSource = CurrentWebAPIConfig.listDetailConfig;
                    treeWebAPIDetailConfig.RefreshDataSource();
                }
            }
        }

        private void toolStripButton14_Click(object sender, EventArgs e)
        {
            CopyCollectWebAPIConfig = (gridWebAPI.DataSource as List<CollectWebAPIConfig>).ToJSON().FromJSON<List<CollectWebAPIConfig>>();
            XtraMessageBox.Show("复制成功");
        }

        private void toolStripButton15_Click(object sender, EventArgs e)
        {
            if (CopyCollectWebAPIConfig.Count > 0)
            {
                //gridWebAPI.DataSource = CopyCollectWebAPIConfig.ToJSON().FromJSON<List<CollectWebAPIConfig>>();
                var pasteJSONConfig = CopyCollectWebAPIConfig.ToJSON().FromJSON<List<CollectWebAPIConfig>>();
                foreach (var webDetail in pasteJSONConfig)
                {
                    var jsonConfigDetail = webDetail.listDetailConfig;
                    foreach (var item in jsonConfigDetail)
                    {
                        string oldConfigID = item.EquipWebAPIConfigDeID;
                        item.EquipWebAPIConfigDeID = Guid.NewGuid().ToString("N");
                        //所有父级节点的都统一更改
                        var childOldConfig = jsonConfigDetail.Where(x => x.ParentID == oldConfigID).ToList();
                        foreach (var childItem in childOldConfig)
                        {
                            childItem.ParentID = item.EquipWebAPIConfigDeID;
                        }
                    }
                }
                gridWebAPI.DataSource = pasteJSONConfig;
            }
        }
    }







}

